<?php

namespace app\utils;

use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

/*
 * https://github.com/Seldaek/monolog
 * composer require monolog/monolog
 */
class Log{

    private static $logdir = null;

    private static $logger = null;

    private static $today = null;

    private static $formatter = null;

    public static function info($content){
        echo '[' . date('Y-m-d H:i:s') . '] ' . $content . "\n";
        self::getLogger()->info($content);
    }

    public static function error($content){
        echo '[' . date('Y-m-d H:i:s') . '] ' . $content . "\n";
        self::getLogger()->error($content);
    }

    private static function getLogger(){
        if(!self::$logdir){
            self::$logdir = __DIR__ . '/../../logs/';
        }
        if(!self::$logger){
            self::$logger = new Logger('');
            self::$today = date('Y-m-d');
            $stream = new StreamHandler(self::$logdir . '/' . self::$today . '.txt', Logger::INFO);
            self::$formatter = new LineFormatter("[%datetime%]%level_name%: %message%\n", "H:i:s");
            $stream->setFormatter(self::$formatter);
            self::$logger->pushHandler($stream);
        }
        if(self::$today != date('Y-m-d')){
            self::$today = date('Y-m-d');
            $stream = new StreamHandler(self::$logdir . '/' . self::$today . '.txt', Logger::INFO);
            $stream->setFormatter(self::$formatter);
            self::$logger->setHandlers([$stream]);
        }
        return self::$logger;
    }
}